package com.spgf.controller.utils;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Toast;

import com.archtecture.model.exceptions.NegocioException;
import com.spgf.model.utils.AndroidUtil;

public abstract class PadraoFragmentAb extends Fragment {

	// @formatter:off
	protected Button.OnClickListener	acaoExecutar	= new Button.OnClickListener() {

		@Override
		public void onClick(final View pView) {

			try {
				executarClick(pView);
			} catch (final NegocioException e) {
				Toast.makeText(pView.getContext(), AndroidUtil.obterMensagemErro(e), Toast.LENGTH_LONG).show();
			}
		}
	};

	protected OnItemSelectedListener	acaoSelecionar	= new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> pParent, View pView, int pPosition, long pID) {
			try {
				executarSelecao(pParent, pView, pPosition, pID);
			} catch (final NegocioException e) {
				Toast.makeText(pView.getContext(), e.getMensagemErro().toString(), Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {}

	};
	
	protected OnItemLongClickListener	acaolongClick	= new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> pParent, View pView, int pPosition, long pID) {
			try {
				return executarLongClick(pParent, pView, pPosition,pID);
			} catch (final NegocioException e) {
				Toast.makeText(pView.getContext(), e.getMensagemErro().toString(), Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		
	};
	
	//@formatter:on

	public abstract void configurarTela(ViewGroup pRoot) throws NegocioException;

	protected boolean executarLongClick(AdapterView<?> pParent, View pView, int pPosition, long pID) throws NegocioException {
		return false;
	}

	protected void executarSelecao(AdapterView<?> pParent, View pView, int pPosition, long pID) throws NegocioException {}

	protected void executarClick(View pView) throws NegocioException {}

	@Override
	public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {

		final ViewGroup root = configurarViewRoot(inflater);

		try {
			configurarTela(root);
		} catch (final NegocioException e) {
			Toast.makeText(root.getContext(), e.getMensagemErro().toString(), Toast.LENGTH_SHORT).show();
		}

		return root;
	}

	protected abstract ViewGroup configurarViewRoot(final LayoutInflater inflater);
}
